import React, { useState } from 'react';
import List from './List.jsx';

const CommentApp = () => {
  const [name, setName] = useState('');
  const [msg, setMsg] = useState('');
  const [rating, setRating] = useState();
  const [comments, setComments] = useState([]);
  const [filterCondition, setFilterCondition] = useState('ALL');

  function handleNameChange(e) {
    setName(e.target.value)
  }
  function handleMsgChange(e) {
    setMsg(e.target.value)
  }
  function handleRatingChange(e) {
    setRating(Number(e.target.value))
  }
  function submit() {
    const newComments = comments.concat({
      name,
      msg,
      rating
    })
    setComments(newComments)
    setName('')
  }

  function handleFiterConditionChangeToAll() {
    setFilterCondition('ALL')
  }

  function handleFiterConditionChangeTo5() {
    setFilterCondition('5')
  }

  const commentsWithFilter = comments.filter(item => Number(item.rating) === Number(filterCondition))
  
  return (
    <div data-testid="app" className="app">
      <input value={name} onChange={handleNameChange} />
      <input value={msg} onChange={handleMsgChange} />
      <input value={rating} onChange={handleRatingChange} />
      <button onClick={submit}>提交</button>
      <button onClick={handleFiterConditionChangeToAll}>all</button>
      <button onClick={handleFiterConditionChangeTo5}>5分</button>
      <List comments={filterCondition === 'ALL' ? comments : commentsWithFilter} />
    </div>
  );
};

export default CommentApp;
